import { defineStore } from "pinia";
import { store } from "../index";

interface AdminMenus {
  menus: AdminLoginMenus[];
  crumber: { [index: string]: string };
  isCollapse: boolean;
}

export const useAdminState = defineStore("user", {
  state(): AdminMenus {
    return {
      menus: [],
      crumber: {},
      isCollapse: false,
    };
  },
  getters: {
    // 处理成二级数组
    getMenusList(state) {
      const newMenus: { [key: string]: AdminLoginMenus } = {};
      state.menus.forEach((item) => {
        if (item.parentId === 0) {
          // 如果是一级权限就给newMenus新增一个key为id的键值对
          newMenus[item.id] = {
            ...item,
            children: newMenus[item.id]?.children,
          };
        } else {
          // 处理遍历时，第一个路由不是一级权限的问题
          newMenus[item.parentId] ??= {} as AdminLoginMenus;
          // 确保每个数据都存在children属性
          newMenus[item.parentId].children ??= [];
          // 如果item的父级存在children属性,就push进去
          newMenus[item.parentId].children?.push(item);
        }
      });
      return newMenus;
    },
  },
  actions: {
    updateMenus(menus: AdminLoginMenus[]) {
      this.menus = menus;
    },
    Collapse(e: boolean) {
      console.log(e);
      this.isCollapse = !e;
    },
  },
});

// 导出非vue文件的数据(因为没有setup)
export const useAdminStatewithout = () => useAdminState(store);
